package com.example.springboot.utils.TimerTask;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


/**
 * 计时任务（依赖与hashmap数据结构，结合线程池中特定线程的睡眠实现计时功能）
 */
@Component
public class TimerTask {
    @Resource
    private TimerHashMap timer;
    @Resource
    private ThreadPoolTaskExecutor userThreadPoolTaskExecutor;

    /**
     * 计时任务的注册与任务完毕后的销毁以及存留
     * @param serverKey 计时任务标识字段
     * @param taskInfo 计时任务信息
     */
    public void setTimer(String serverKey, TaskInfo taskInfo) {
        boolean sign = timer.containsKey(serverKey);
        if (sign)
            return;
        try {
            userThreadPoolTaskExecutor.execute(
                    new Thread(
                            () -> {
                                TaskInfo put = timer.put(serverKey, taskInfo);
                                if (put == null) {
                                    try {
                                        System.out.println(Thread.currentThread().getName()+serverKey+"计时开始------>");
                                        Thread.sleep(taskInfo.getTaskTime());
                                        if (taskInfo.getType() == TaskType.TASK_DELETE_CACHE) {
                                            TaskInfo remove = timer.remove(serverKey);
                                            if (remove == null)
                                                throw new Exception("计时任务删除失败");
                                        }else if (taskInfo.getType()== TaskType.TASK_INTER_CACHE){
                                            boolean result = timer.endTaskInCache(serverKey, taskInfo);
                                            if (!result){
                                                throw new Exception("计时任务无法正常结束");
                                            }
                                        }else {
                                            /*将计时任务插入计时任务数据库.....*/
                                        }
                                        System.out.println(Thread.currentThread().getName()+serverKey+"任务结束------>");
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            },
                            serverKey
                    )
            );
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断计时任务是否结束
     * @param serverKey 计时任务标识字段
     * @return 是否已经结束
     */
    public boolean taskIsEnd(String serverKey){
        boolean result = timer.containsKey(serverKey);
        if (result){
            return timer.get(serverKey).getTaskTime() == 0;
        }
        return false;
    }
}
